#!/usr/bin/env bash
# SPDX-FileCopyrightText: 2022 Caleb La Grange <thonkpeasant@protonmail.com>
# SPDX-License-Identifier: GPL-3.0-only

Fail(){
	printf "${@}\n"
	exit 1
}

Set_placeholder(){
	git config user.name || git config user.name 'osbmkplaceholder'
	git config user.email || git config user.email 'placeholder@osbmkplaceholder.com'
}

Clean(){
	if [ "$(git config user.name)" = "osbmkplaceholder" ]; then
		git config --unset user.name
	fi

	if [ "$(git config user.email)" = "placeholder@osbmkplaceholder.com" ]; then
		git config --unset user.email
	fi
}

Revision_check(){
	name=${1}
	while read -r line ; do
		set ${line} >/dev/null 2>&1
		case ${line} in
			rev:*)
			revision=${2}
			;;
			loc:*)
			location=${2}
			;;
			url:*)
			url=${2}
			;;
			bkup_url:*)
			bkup_url=${2}
			;;
		esac
	done <<< $(eval "awk ' /\{.*${name}.*}{/ {flag=1;next} /\}/{flag=0} flag { print }' resources/git/revisions")

	# Do not check for non-existent projects
	if [ ! -d ${location} ]; then
		return 0
	fi

	_cur_revision=$(cd ${location} && git rev-parse --verify HEAD)
	if [ "${_cur_revision}" = "${revision}" ]; then
		return 0
	elif $(git log -n15 --format=format:"%H" | grep -q "${revision}") ; then 
		return 0
	else
		(
		cd ${location} || return 1

		# Avoid accidentally operating on parent git
		if [ ! -d '.git/' ]; then
			return 0
		fi

		# For modules with patches, the current git hash will be wrong, but the correct one
		# will be somewhere in the log.
		if $(git log -n15 --format=format:"%H" | grep -q "${revision}") ; then 
			return 0
		else
			printf "WARNING: gitmodule ${name} is behind the current version in osbmk\nRun: './download gitmodule ${name}' to make sure you're at the latest version"
		fi
		)
	fi
}

Check_versions(){
	gitmodules=$(awk -F '[{}]' '/^{.*}{/ {print $2}' resources/git/revisions)
	for gitmodule in ${gitmodules} ; do
		Revision_check "${gitmodule}"
	done
}

Run(){
if [ ! -d ".git/" ]; then
	git init
fi

if [ "${1}" = "clean" ]; then
	Clean
else
	# Check if username and or email is set.
	if ! git config user.name || git config user.email ; then
		Set_placeholder
	fi
fi
}

Run >/dev/null
Check_versions
